import sys

import sqlparse
from project_sqllineage.ParseSQL import ParseSQL
from project_sqllineage.GenerateTree import GenerateTree
from project_sqllineage.ParseTree import ParseTree
from project_sqllineage.SqlparseSqllineage import SqlparseSqllineage
from project_sqllineage.StarReplace import StarReplace


def main():
    # sql = '''
    #     insert into fdm.tab_10
    #     select t1.col_1,t1.col_2,t2.col_3,t3.*
    #     from odm.tab_1 t1
    #     join (select col_3,col_4 from odm.tab_2) t2
    #     on t1.col_3 = t2.col_3
    #     join (select col_5,col_6 from odm.tab_3) t3
    #     on t1.col_5 = t3.col_5
    #     where t1.startdate = sysdate
    #     union all
    #     select t4.col_1,t4.col_2,t4.col_7,t6.*
    #     from odm.tab_4 t4
    #     join (select t5.col_7,t5.col_8 from (select * from odm.tab_5) t5) t6
    #     on t4.col_7 = t6.col_7
    #     join (select col_9,col_10 from odm.tab_6) t7
    #     on t4.col_9 = t7.col_9
    # '''
    # sql = '''insert into tab_src select (t3.a * t3.b)/100,t3.col3,t1.* from tab_t1 t1 left join (select * from tab_t1 t2 ) t3 on t1.id = t3.id left join (select count(*),id from tab_t4 group by id) t4 on t1.id = t4.id where t1.time = sysdate and t1.id like \'%*%\' order by t1.time;'''
    # sql = '''insert into tab select t1.name, t1.age, t2.* from tab_1 t1 join (select tt1.* from tab_11 tt1 join tab_22 tt2 on tt1.id = tt2.id) t2 on t1.id = t2.id where t1.date = sysdate;'''
    # sql = '''insert into tab select t1.name, t1.age, t2.* from tab_1 t1 join (select tt1.a,tt2.b from tab_11 tt1 join (select * from tab_11 )tt2 on tt1.id = tt2.id) t2 on t1.id = t2.id where t1.date = sysdate;'''

    try:
        sql_schema = sys.argv[1]
        sql = sys.argv[2]
        sql = sqlparse.format(sql.upper(),strip_comments=True).strip()
        sql = sql.replace('\n',' ').replace('\r\n',' ')

        parsed = sqlparse.parse(sql)[0]
        parsesql = ParseSQL()
        parsesql.ast_table_list.clear()
        result_list = parsesql.parse_level(parsed,0,-1,False,False,-1)

        generatetree = GenerateTree()
        generatetree.ast_table_tree_list.clear()
        tree = generatetree.generateTree(result_list)

        parsetree = ParseTree(sql_schema=sql_schema)
        parsetree.mapping_star_to_table.clear()
        columnlist = parsetree.parseTree(tree)

        starreplace = StarReplace()
        finalsql = starreplace.handingColumn(sql,columnlist)

        print(finalsql)

        sqlparsesqllineage = SqlparseSqllineage()
        sqlparsesqllineage.analysis(str(finalsql))
        # sqlparsesqllineage.analysis_dialect(str(finalsql))
    except Exception as e:
        print(str(e))

if __name__ == '__main__':
    main()
